package com.leemon.mall.common.util;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

/**
 * @author limenglong
 * @create 2019-09-09 17:42
 * @desc
 **/
@Component
public class CacheManagerUtil {
    @Autowired
    private CacheManager cacheManager;


    public <T> T getCache(String cacheName, String key) {

        Cache cache = cacheManager.getCache(cacheName);
        if (ObjectUtil.isEmpty(cache)) {
            return null;
        }

        Cache.ValueWrapper valueWrapper = cache.get(key);
        if (ObjectUtil.isEmpty(valueWrapper)) {
            return null;
        }
        return (T) valueWrapper.get();
    }

    public void putCache(String cacheName, String key, Object value) {
        Cache cache = cacheManager.getCache(cacheName);
        if (ObjectUtil.isNotEmpty(cache)) {
            cache.put(key, value);
        }
    }

    public void evictCache(String cacheName, String key) {
        Cache cache = cacheManager.getCache(cacheName);
        if(ObjectUtil.isNotEmpty(cache)){
            cache.evict(key);
        }
    }

}
